//全局Ajax配置
var lastTimeout = null;
$.ajaxSetup({
    //global: false,
    type: "POST",
    dataFilter: function (data) {
        var result = eval("(" + data + ")");

        if (typeof result == "object" && typeof result.success != "undefined") {

            if (result.success === false) {
                if (typeof result.session_timeout != "undefined" && result.session_timeout === true) {
                    if (!lastTimeout || new Date().getTime() - lastTimeout > 1500) {
                        lastTimeout = new Date().getTime();

                        var popLoginWin = $("#popLoginWin");
                        if (popLoginWin.length === 0) {
                            $("<div id='popLoginWin' style='padding:20px 30px;'><table><tr><td colspan='2' style='color:#888;'>登录已超时，请重新登录</td></tr><tr><td style='width:45px;'>帐号：</td><td><input name='UserName'/></td></tr><tr><td>密码：</td><td><input type='password' name='UserPassword' /></td></tr><tr><td>&nbsp;</td><td><input class='btnPopLogin' type='button' value='登录' style='width:60px; height:28px;'/><img class='imgPopLoading' src='/images/load_1.gif' style='display:none;'/></td></tr></table></div>").appendTo("body");
                            $("#popLoginWin").window({
                                title: "&nbsp;登录",
                                iconCls: "icon-key",
                                width: 285,
                                height: 190,
                                minimizable: false,
                                maximizable: false,
                                collapsible: false,
                                resizable: false,
                                modal: true
                            });
                            $(".btnPopLogin").click(function () {
                                $(".btnPopLogin").attr("disabled", true);
                                $(".imgPopLoading").show();
                                YZ.createPost({
                                    url: "/Service/Customer.CustomerService.CustomerLogin",     //服务地址
                                    before: function (p) {
                                        p.UserName = $("[name='UserName']").val();
                                        p.UserPassword = $("[name='UserPassword']").val();
                                        return p;
                                    },
                                    success: function (result) {
                                        $(".imgPopLoading").hide();
                                        if (result == 4 || result == 5) {
                                            $("#popLoginWin").window("close");
                                        }
                                        else if (result == 3) {
                                            alert("您输入的帐号或密码不正确，请重新输入");
                                        }
                                    }
                                });
                            });
                        }
                        $("#popLoginWin").window("open");
                        $(".imgPopLoading").hide();
                        $(".btnPopLogin").removeAttr("disabled");
                        $("[name='username']").focus();
                        //$.messager.alert("提示", "登录超时");
                    }
                    return [];
                }

                if ($(this).length > 0 && $(this)[0].failure) {
                    $(this)[0].failure(result);
                    $(this)[0].isFailure = true;
                }
                else {
                    $.messager.alert("提示", result.exceptionMsg);
                }
                return [];
            }
            return JSON.stringify(result.result);
        }
        else {
            return data;
        }
    }
});

//--------------------------------------------------------
//                      FormToJson
//--------------------------------------------------------
function $getForm() {
    var elements = new Array();

    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        if (arguments.length == 1)
            return element;
        elements.push(element);
    }
    return elements;
}
//转换的主要函数
function formToJSON(f) {
    var form = $getForm(f);
    if (form == null) {
        return "";
    }
    var json = '{';
    var isarray = false;
    for (var i = 0, max = form.elements.length; i < max; i++) {
        var e = form.elements[i];
        var name = e.name;
        if (!name || name === "") {
            continue;
        }
        if (name.substring(name.length - 2) == '[]') {
            name = name.substring(0, name.length - 2);
            lastarr = name;
            if (isarray === false) {
                json += '"' + name + '":[';
            }
            isarray = true;
        } else {
            if (isarray) {
                json = json.substring(0, json.length - 1) + '],';
            }
            isarray = false;
        } //end else

        switch (e.type) {
            case 'checkbox':
            case 'radio':
                if (!e.checked) { break; }
            case 'hidden':
            case 'password':
            case 'file':
            case 'text':
                if (!isarray) {
                    json += '"' + name + '":';
                }
                //                json += '"' + e.value.replace(new RegExp('(["\\\\])', 'g'), '\\$1') + '",';
                json += JSON.stringify(e.value) + ',';
                break;
            case 'button':
            case 'image':
            case 'reset':
            case 'submit':
            default:
                {
                    if (e.tagName.toLowerCase() == "textarea") {
                        if (!isarray) {
                            json += '"' + name + '":';
                        }
                        //                        json += '"' + e.value.replace(new RegExp('(["\\\\])', 'g'), '\\$1') + '",';
                        json += JSON.stringify(e.value) + ',';
                        break;
                    }
                }
        } //end switch
    } //end for

    var tempResult = json.substring(0, json.length - 1);
    if (tempResult === "") {
        return {};
    }

    //return json.substring(0, json.length - 1) + '}';
    return eval("(" + json.substring(0, json.length - 1) + '}' + ")");
}

////--------------------------------------------------------
////                      CreatePost
////--------------------------------------------------------
var YZ = {};


YZ.formatDecimal = function (number, decimals, fillzero) {
    /// <summary>格式化小数</summary>
    /// <param name="number" type="int">要格式化的数字</param>
    /// <param name="decimals" type="int">保留小数位数</param>
    /// <param name="fillzero" type="bool">不足位数是否自动补零</param>
    /// <returns type="string" />
    var n = number ? parseFloat(number) : 0;
    var p = Math.pow(10, decimals);
    n = Math.round(n * p) / p;
    n = n || 0;
    var ns = n.toString();
    if (fillzero) {
        var pos = ns.lastIndexOf(".");
        if (pos < 1) {
            ns += ".";
        }
        var decs = pos < 1 ? 0 : (ns.substring(pos + 1)).length;
        for (var i = 0; i < decimals - decs; i++) ns += "0";
    }
    return ns;
};

YZ.createPost = function (opts) {
    /// <summary>创建Ajax请求</summary>
    /// <param name="opts">请求参数</param>
    /// <remarks>form</remarks>
    var formData = {};

    //form
    if (opts.form) {

        if (!document.getElementById(opts.form)) {
            $.messager.alert("提示", "请确认" + opts.form + "是否存在，该问题导致数据提交失败.");
            return false;
        }

        if ($.isArray(opts.form)) {
            $.each(opts.form, function (i, item) {
                formData[item.mapping] = formToJSON(item.id);
            });
        }
        else {
            formData = formToJSON(opts.form);
        }
    }

    //before
    if (opts.before) {
        formData = opts.before(formData);

        if (!formData) {
            return false;
        }
    }

    //url
    var url = "/Service/Index";
    if (opts.url) {
        url = opts.url;
    }

    var postData = {};
    postData.ParamString = JSON.stringify(formData);
    if (opts.pageSize) {
        postData.rows = opts.pageSize;
    }
    if (opts.pageIndex) {
        postData.page = opts.pageIndex;
    }

    $.ajax({
        url: url,
        type: "post",
        data: postData,
        success: function (result) {
            if ($(this)[0].isFailure) {
                return;
            }

            if (opts.success) {
                opts.success(result);
            }
            else {

            }
        },
        failure: function (result) {
            if (opts.failure) {
                opts.failure(result.exceptionMsg);
            }
            else {
                if ($.messager) {
                    $.messager.alert("提示", result.exceptionMsg);
                }
                else {
                    alert(result.exceptionMsg);
                }
            }
        }
    });
};

//eg:
//YZ.convertListToTree({
//  idField:"",
//  textField:"",
//  parentIdField:""
//}, sourceList);
YZ.convertListToTree = function (config, rows) {
    //过滤
    for (var i = 0; i < rows.length; i++) {
        rows[i].id = rows[i][config.idField];
        rows[i].text = rows[i][config.textField];
        rows[i].parentId = rows[i][config.parentIdField];
        if (rows[i][config.urlField]) {
            rows[i].url = rows[i][config.urlField];
        }
        if (rows[i][config.checkedField]) {
            rows[i].checked = rows[i][config.checkedField];
        }
        if (rows[i][config.iconField]) {
            rows[i].iconCls = rows[i][config.iconField];
        }
    }
    //递归结果
    var tree = [];
    recursionMenuList(rows, tree, 0);
    return tree;
};

//--------------------------------------------------------
//                      递归树型结构
//--------------------------------------------------------
function recursionMenuList(resultTree, menuTree, menuID) {
    for (var i = 0; i < resultTree.length; i++) {
        if (resultTree[i].parentId == menuID) {

            var item = resultTree[i];
            item.children = [];
            menuTree.push(item);
            recursionMenuList(resultTree, item.children, item.id);
            if (item.children.length === 0) {
                item.leaf = true;
            }
        }
    }
}


////--------------------------------------------------------
////                      JSON
////--------------------------------------------------------

if (!this.JSON) { this.JSON = {}; }
(function () {
    function f(n) { return n < 10 ? '0' + n : n; }
    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function (key) {
            return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
        }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); };
    }
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }
    function str(key, holder) {
        var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); }
        if (typeof rep === 'function') { value = rep.call(holder, key, value); }
        switch (typeof value) {
            case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; }
                gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') {
                    length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; }
                    v = partial.length === 0 ? '[]' : gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v;
                }
                if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } }
                v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v;
        }
    }
    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {
            var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; }
            rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); }
            return str('', { '': value });
        };
    }
    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {
            var j; function walk(holder, key) {
                var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } }
                return reviver.call(holder, key, value);
            }
            text = String(text); cx.lastIndex = 0; if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; }
            throw new SyntaxError('JSON.parse');
        };
    }
}());



////--------------------------------------------------------
////                      EasyUI Extends
////--------------------------------------------------------

///**
//* From扩展
//* getData 获取数据接口
//*
//* @param {Object} jq
//* @param {Object} params 设置为true的话，会把string型"true"和"false"字符串值转化为boolean型。
//*/
if ($.fn.form) {
    $.extend($.fn.form.methods, {
        getData: function (jq, params) {
            var formArray = jq.serializeArray();
            var oRet = {};
            for (var i in formArray) {
                if (typeof (oRet[formArray[i].name]) == 'undefined') {
                    if (params) {
                        oRet[formArray[i].name] = (formArray[i].value == "true" || formArray[i].value == "false") ? formArray[i].value == "true" : formArray[i].value;
                    }
                    else {
                        oRet[formArray[i].name] = formArray[i].value;
                    }
                }
                else {
                    if (params) {
                        oRet[formArray[i].name] = (formArray[i].value == "true" || formArray[i].value == "false") ? formArray[i].value == "true" : formArray[i].value;
                    }
                    else {
                        oRet[formArray[i].name] += "," + formArray[i].value;
                    }
                }
            }
            return oRet;
        }
    });
}

////扩展jQuery对json字符串的转换
jQuery.extend({
    /** * @see 将json字符串转换为对象 * @param json字符串 * @return 返回object,array,string等对象 */
    evalJSON: function (strJson) {
        return eval("(" + strJson + ")");
    },
    /** * @see 将javascript数据类型转换为json字符串 * @param 待转换对象,支持object,array,string,function,number,boolean,regexp * @return 返回json字符串 */
    toJSON: function (object) {
        return JSON.stringify(object);
    }
});


//请求数据前事件方法工厂
function beforeLoadHandler(controlType, attachHandler) {
    var fun = function () {
        var param;
        if (arguments.length == 2) {
            param = arguments[1];
        }
        else {
            param = arguments[0];
        }

        var ctrl, searchParam;
        if ($(this)[controlType]) {
            ctrl = $(this)[controlType]("options");
        }

        if (ctrl) {
            //自动加载为false的话，默认不加载数据，直到reload或load
            if (ctrl.autoload === false) {
                ctrl.autoload = true;
                return false;
            }
        }

        //请求前参数处理器
        var result = {};

        //form
        if (ctrl.form) {
            if (!document.getElementById(ctrl.form)) {
                $.messager.alert("提示", "请确认" + ctrl.form + "是否存在，该问题导致load失败.");
                return false;
            }
            if ($.isArray(ctrl.form)) {
                $.each(ctrl.form, function (i, item) {
                    result[item.mapping] = formToJSON(item.id);
                });
            }
            else {
                result = formToJSON(ctrl.form);
            }
        }

        if (ctrl.before) {
            result = ctrl.before(result);
            if (result === false) {
                return false;
            }
        }
        //附加参数处理器
        if (result) {
            if (attachHandler) {
                result = attachHandler(result, $(this), param);
            }
            param.ParamString = $.toJSON(result);
        }

        return param;
    };
    return fun;
}

//数据过滤事件方法工厂
function loadFilterHandler(controlType, attachHandler) {
    var fun = function (data) {
        var ctrl, searchParam;
        if ($(this)[controlType]) {
            ctrl = $(this)[controlType]("options");
        }

        if (ctrl) {
            searchParam = ctrl.service;
            data.__service = ctrl.service;
        }

        if (!searchParam) {
            return data;
        }

        if (attachHandler) {
            data = attachHandler(data);
        }

        if (searchParam.filter) {
            data = searchParam.filter(data);
        }
        return data;
    };
    return fun;
}

//加载成功事件方法工厂
function loadSuccessHandler(controlType, attachHandler) {
    var fun = function (data) {
        var ctrl, searchParam;
        if ($(this)[controlType]) {
            ctrl = $(this)[controlType]("options");
        }

        if (ctrl && ctrl.success) {
            ctrl.success(data);
        }

        if (attachHandler) {
            attachHandler(data, $(this));
        }
    };
    return fun;
}

////Panel默认配置
////-------------------------------------------------------------
if ($.fn.panel) {
    $.extend($.fn.panel.defaults, {
        loadingMessage: "正在加载",
        border: true,
        style: { padding: "1px" }
    });
}

////Pagination默认配置
////-------------------------------------------------------------
if ($.fn.pagination) {
    $.extend($.fn.pagination.defaults, {
        beforePageText: "",
        afterPageText: "页 / {pages}页",
        displayMsg: "第 <b>{from}</b> 至 <b>{to}</b> 条记录，共 <b>{total}</b> 条记录"
    });
}

////datagrid默认配置
////-------------------------------------------------------------
if ($.fn.datagrid) {
    $.extend($.fn.datagrid.defaults, {
        //url: '/fw/ajax/AjaxHandler.ashx',
        loadMsg: "正在加载",
        pagination: true,
        //iconCls: 'icon-save',
        autoload: true,
        nowrap: false,
        autoRowHeight: false,
        striped: true,
        collapsible: false,
        rownumbers: true,
        singleSelect: true,
        remoteSort: false,
        fit: true,
        loadFilter: function (data) {
            //数据适配
            if (data.Data) {
                if (data.FooterData) {
                    return { rows: data.Data, total: data.TotalCount, footer: data.FooterData };
                }
                return { rows: data.Data, total: data.TotalCount };
            }
            return { rows: data };
        },
        onBeforeLoad: beforeLoadHandler("datagrid"),
        onLoadSuccess: loadSuccessHandler("datagrid")
    });
}

////combobox默认配置
////-------------------------------------------------------------
if ($.fn.combobox) {
    $.extend($.fn.combobox.defaults, {
        //url: '/fw/ajax/AjaxHandler.ashx',
        mode: "remote",
        onBeforeLoad: beforeLoadHandler("combobox", function (p, ob) {
            var text = ob.combobox("getText");
            p.q = text;
            return p;
        }),
        onLoadSuccess: loadSuccessHandler("combobox", function (d, ob) {
            if (d.length > 0) {
                if (d[0].value || d[0].value === "") {
                    ob.combobox("select", d[0].value);
                }
                else {
                    ob.combobox("select", null);
                }
            }
        })
    });
}

//combogrid默认配置
//-------------------------------------------------------------
if ($.fn.combogrid) {
    $.extend($.fn.combogrid.defaults, {
        //url: '/fw/ajax/AjaxHandler.ashx',
        mode: "remote",
        pageSize: 10,
        pageList: [5, 10, 15, 20],
        panelWidth: 300,
        panelHeight: 310,
        remoteSort: false,
        pagePosition: "bottom",
        rownumbers: false,
        onShowPanel: function () {
            $(this).combogrid("grid").datagrid("getPager").pagination({
                showPageList: false,
                displayMsg: "共{total}条",
                beforePageText: "",
                afterPageText: "/{pages}页"
            });
        },
        loadFilter: loadFilterHandler("datagrid", function (data) {
            //数据适配
            if (data.Data) {

                return { rows: data.Data, total: data.TotalCount };
            }
            return { rows: data };
        }),
        onBeforeLoad: beforeLoadHandler("datagrid", function (p, ob, sourceParam) {
            if (sourceParam.q) {
                p.q = sourceParam.q;
            }
            return p;
        })
    });
}

//Tree默认配置
//-------------------------------------------------------------
if ($.fn.tree) {
    $.extend($.fn.tree.defaults, {
        //url: '/fw/ajax/AjaxHandler.ashx',
        loadFilter: loadFilterHandler("tree", function (data) {
            var rows = data.Data ? data.Data : data;
            //获取配置的服务
            var config = data.__service;
            //过滤
            for (var i = 0; i < rows.length; i++) {
                rows[i].id = rows[i][config.idField];
                rows[i].text = rows[i][config.textField];
                rows[i].parentId = rows[i][config.parentIdField];
                if (rows[i][config.urlField]) {
                    rows[i].url = rows[i][config.urlField];
                }
                if (rows[i][config.checkedField]) {
                    rows[i].checked = rows[i][config.checkedField];
                }
                if (rows[i][config.iconField]) {
                    rows[i].iconCls = rows[i][config.iconField];
                }
            }
            //递归结果
            var tree = [];

            recursionMenuList(rows, tree, 0);
            return tree;
        }),
        onBeforeLoad: beforeLoadHandler("tree", function (p, ob, sourceParam) {
            return p;
        })
    });
}


//TreeGrid默认配置
//-------------------------------------------------------------
if ($.fn.treegrid) {
    $.extend($.fn.treegrid.defaults, {
        //url: '/fw/ajax/AjaxHandler.ashx',
        loadFilter: loadFilterHandler("datagrid", function (data) {
            var rows = data.Data ? data.Data : data;
            var config = data.__service;
            //过滤
            for (var i = 0; i < rows.length; i++) {
                rows[i].id = rows[i][config.idField];
                rows[i].text = rows[i][config.textField];
                rows[i].parentId = rows[i][config.parentIdField];
                if (rows[i][config.urlField]) {
                    rows[i].url = rows[i][config.urlField];
                }
                if (rows[i][config.checkedField]) {
                    rows[i].checked = rows[i][config.checkedField];
                }
                if (rows[i][config.iconField]) {
                    rows[i].iconCls = rows[i][config.iconField];
                }
            }
            //递归结果
            var tree = [];
            recursionMenuList(rows, tree, 0);
            return tree;
        }),
        onBeforeLoad: beforeLoadHandler("datagrid", function (p, ob, sourceParam) {
            return p;
        })
    });
}

//ComboTree默认配置
//-------------------------------------------------------------
if ($.fn.combotree) {
    $.extend($.fn.combotree.defaults, {
        //url: '/fw/ajax/AjaxHandler.ashx',
        loadFilter: loadFilterHandler("tree", function (data) {
            var rows = data.Data ? data.Data : data;
            var config = data.__service;
            //过滤
            for (var i = 0; i < rows.length; i++) {
                rows[i].id = rows[i][config.idField];
                rows[i].text = rows[i][config.textField];
                rows[i].parentId = rows[i][config.parentIdField];
                if (rows[i][config.urlField]) {
                    rows[i].url = rows[i][config.urlField];
                }
                if (rows[i][config.checkedField]) {
                    rows[i].checked = rows[i][config.checkedField];
                }
                if (rows[i][config.iconField]) {
                    rows[i].iconCls = rows[i][config.iconField];
                }
            }
            //递归结果
            var tree = [];
            recursionMenuList(rows, tree, 0);
            return tree;
        }),
        onBeforeLoad: beforeLoadHandler("tree", function (p, ob, sourceParam) {
            return p;
        })
    });
}


//四舍五入，保留小数点后两位，如果不满两位，不满两位则补零
function roundNumber(number, decimals) {
    var newString;// The new rounded number
    decimals = Number(decimals);
    if (decimals < 1) {
        newString = (Math.round(number)).toString();
    } else {
        var numString = number.toString();
        if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
            numString += ".";// give it one at the end
        }
        var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
        var d1 = Number(numString.substring(cutoff, cutoff + 1));// The value of the last decimal place that we'll end up with
        var d2 = Number(numString.substring(cutoff + 1, cutoff + 2));// The next decimal, after the last one we want
        if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
            if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
                while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
                    if (d1 != ".") {
                        cutoff -= 1;
                        d1 = Number(numString.substring(cutoff, cutoff + 1));
                    } else {
                        cutoff -= 1;
                    }
                }
            }
            d1 += 1;
        }
        if (d1 == 10) {
            numString = numString.substring(0, numString.lastIndexOf("."));
            var roundedNum = Number(numString) + 1;
            newString = roundedNum.toString() + '.';
        } else {
            newString = numString.substring(0, cutoff) + d1.toString();
        }
    }
    if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
        newString += ".";
    }
    var decs = (newString.substring(newString.lastIndexOf(".") + 1)).length;
    for (var i = 0; i < decimals - decs; i++) newString += "0";
    return newString;
}

////表单验证,BY TERRY
////-------------------------------------------------------------
if ($.fn.validatebox) {
    $.extend($.fn.validatebox.defaults.rules, {
        enStr: {// 字母数字结合，2-20个字符
            validator: function (value) {
                return /^[A-Za-z0-9]{2,20}$/i.test(value);
            },
            message: '字符为字母数字结合，2-20个字符'
        },
        certStr: {// 证书号格式
            validator: function (value) {
                return /^[-A-Za-z0-9]{6,13}$/i.test(value);
            },
            message: '证书号由字母、数字和-线组成，字符为6-13位'
        },
        idcard: {// 验证身份证
            validator: function (value) {
                return /^\d{15}(\d{2}[A-Za-z0-9])?$/i.test(value);
            },
            message: '身份证号码格式不正确'
        },
        minLength: {
            validator: function (value, param) {
                return value.length >= param[0];
            },
            message: '请输入至少2个字符.'
        },
        length: {
            validator: function (value, param) {
                var len = $.trim(value).length;
                return len >= param[0] && len <= param[1];
            },
            message: "输入内容长度必须介于{0}和{1}之间."
        },
        phone: {// 验证电话号码
            validator: function (value) {
                return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value);
            },
            message: '格式不正确,请使用下面格式:020-88888888'
        },
        mobile: {// 验证手机号码
            validator: function (value) {
                return /^(13|15|18)\d{9}$/i.test(value);
            },
            message: '手机号码格式不正确'
        },
        intOrFloat: {// 验证整数或小数
            validator: function (value) {
                return /^\d+(\.\d+)?$/i.test(value);
            },
            message: '请输入数字，并确保格式正确'
        },
        currency: {// 验证货币
            validator: function (value) {
                return /^\d+(\.\d+)?$/i.test(value);
            },
            message: '货币格式不正确'
        },
        qq: {// 验证QQ,从10000开始
            validator: function (value) {
                return /^[1-9]\d{4,9}$/i.test(value);
            },
            message: 'QQ号码格式不正确'
        },
        integer: {// 验证整数 可正负数
            validator: function (value) {
                //return /^[+]?[1-9]+\d*$/i.test(value);

                return /^([+]?[0-9])|([-]?[0-9])+\d*$/i.test(value);
            },
            message: '请输入整数'
        },
        age: {// 验证年龄
            validator: function (value) {
                return /^(?:[1-9][0-9]?|1[01][0-9]|120)$/i.test(value);
            },
            message: '年龄必须是0到120之间的整数'
        },

        chinese: {// 验证中文
            validator: function (value) {
                return /^[\Α-\￥]+$/i.test(value);
            },
            message: '请输入中文'
        },
        english: {// 验证英语
            validator: function (value) {
                return /^[A-Za-z]+$/i.test(value);
            },
            message: '请输入英文'
        },
        unnormal: {// 验证是否包含空格和非法字符
            validator: function (value) {
                return /.+/i.test(value);
            },
            message: '输入值不能为空和包含其他非法字符'
        },
        username: {// 验证用户名
            validator: function (value) {
                return /^[a-zA-Z][a-zA-Z0-9_]{5,15}$/i.test(value);
            },
            message: '用户名不合法（字母开头，允许6-16字节，允许字母数字下划线）'
        },
        faxno: {// 验证传真
            validator: function (value) {
                //            return /^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/i.test(value);
                return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value);
            },
            message: '传真号码不正确'
        },
        zip: {// 验证邮政编码
            validator: function (value) {
                return /^[1-9]\d{5}$/i.test(value);
            },
            message: '邮政编码格式不正确'
        },
        ip: {// 验证IP地址
            validator: function (value) {
                return /d+.d+.d+.d+/i.test(value);
            },
            message: 'IP地址格式不正确'
        },
        name: {// 验证姓名，可以是中文或英文
            validator: function (value) {
                return /^[\Α-\￥]+$/i.test(value) | /^\w+[\w\s]+\w+$/i.test(value);
            },
            message: '请输入姓名'
        },
        date: {// 验证姓名，可以是中文或英文
            validator: function (value) {
                //格式yyyy-MM-dd或yyyy-M-d
                return /^(?:(?!0000)[0-9]{4}([-]?)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-]?)0?2\2(?:29))$/i.test(value);
            },
            message: '清输入合适的日期格式'
        },
        msn: {
            validator: function (value) {
                return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value);
            },
            message: '请输入有效的msn账号(例：abc@hotnail(msn/live).com)'
        },
        same: {
            validator: function (value, param) {
                if ($("#" + param[0]).val() !== "" && value !== "") {
                    return $("#" + param[0]).val() == value;
                } else {
                    return true;
                }
            },
            message: '两次输入的密码不一致！'
        }
    });
}
